package com.sky.aop;

import com.sky.annotation.CleanRedis;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class RedisHandler {

    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut("execution(* com.sky.service.impl.*.*(..))")
    public void pt() {
    }

    @Around("pt()")
    public Object handle(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed = pjp.proceed();

        // 获取方法的签名
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        // 获取方法对象
        Method method = signature.getMethod();
        // 获取方法的注解
        CleanRedis annotation = method.getAnnotation(CleanRedis.class);
        if(annotation!=null){
            log.info("扫描到注解，开始清空redis");
            redisTemplate.delete(annotation.value());
            log.info("redis已清空");
        }

        return proceed;
    }
}
